package personal.xjl.studentdemo.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import personal.xjl.studentdemo.dao.StudentMapper;
import personal.xjl.studentdemo.entity.Student;
import personal.xjl.studentdemo.service.StudentService;

import java.util.List;

@Controller        //控制器,默认对象的名字是类的首写字母小写studentController
@RequestMapping("/Student")
public class StudentController {
    @Autowired  //自动注入下面的对象studentMapper
    StudentService studentService;
    @RequestMapping("list.do")
    //@ResponseBody   //响应内容
    public String list(Model model,@RequestParam(value = "currPage",defaultValue = "1") int currPage,@RequestParam(value = "pageSize",defaultValue = "3") int pageSize) {
        List<Student> studentList=studentService.selectByPage((currPage-1)<0?0:(currPage-1)*pageSize,pageSize);
        System.out.println(studentList);
        //使用model对象将studentList的值以studentList名称带到listStudents.html页面
        model.addAttribute("studentList",studentList);
        model.addAttribute("currPage",currPage);
        return "listStudents";
    }
    @RequestMapping("delete.do")
  //  @ResponseBody
    public String delete(@RequestParam("id") int id,Model model) {
        studentService.deleteStudent(id);
        return "redirect:/Student/list.do";
    }
    @RequestMapping("page.do")
    public String page(@RequestParam("page") String page) {
        return page;
    }
    @RequestMapping("add.do")
    public String add(Student student) {
        System.out.println(student);
        studentService.addStudent(student);
        return "redirect:/Student/list.do";
    }
    //准备修改学生信息
    @RequestMapping("toEdit.do")
    public String edit(@RequestParam("id") int id, Model model) {
        Student oldStudent=studentService.selectById(id);
        model.addAttribute("student",oldStudent);
        return "editStudent";
    }
    //修改学生信息
    @RequestMapping("edit.do")
    public String edit(Student student) {
        studentService.edit(student);
        return "redirect:/Student/list.do";
    }
/*    //登录,如果登录成功，跳转到list.do，显示学生数据；如果登录失败，回到login页面
    @RequestMapping("login.do")
    public String login(HttpSession session, @RequestParam("username") String username, @RequestParam("password") String password) {
        if(studentService.login(username,password)) {
            //发放登录的令牌，username
            session.setAttribute("username",username);
            return "redirect:/Student/list.do";
        }
        else
            return "login";
    }*/
    @RequestMapping("loginNew.do")
    public String loginNew() {
        return "login";
    }
}
